"""
L16设备协议处理器
L16 Device Protocol Handler

处理L16设备的通信协议和数据格式转换
Handles communication protocol and data format conversion for L16 devices
"""

import logging
from typing import Dict, Any, Optional
from pydantic import ValidationError

from ...interfaces.protocol_interface import ProtocolInterface
from .models import L16DataModels

logger = logging.getLogger(__name__)


class L16Protocol(ProtocolInterface):
    """
    L16设备协议处理器
    L16 Device Protocol Handler
    
    实现L16设备的协议解析和响应格式化
    Implements protocol parsing and response formatting for L16 devices
    """
    
    def __init__(self):
        """初始化L16协议处理器 / Initialize L16 protocol handler"""
        self.protocol_version = "1.0"
        self.supported_actions = ["location", "health", "battery", "warning", "audio"]
        self.logger = logging.getLogger(f"{self.__class__.__name__}")
    
    async def parse_request(self, raw_data: Dict[str, Any]) -> Optional[Any]:
        """
        解析L16设备请求数据
        Parse L16 device request data
        
        Args:
            raw_data (Dict[str, Any]): 原始请求数据 / Raw request data
            
        Returns:
            Optional[Any]: 解析后的数据模型 / Parsed data model
            
        Raises:
            ValidationError: 数据验证失败 / Data validation failed
        """
        try:
            # 提取操作类型 / Extract action type
            action = raw_data.get("action")
            if not action:
                self.logger.error("请求数据缺少action字段 / Request data missing action field")
                return None
            
            # 获取对应的数据模型 / Get corresponding data model
            model_class = L16DataModels.get_model(action)
            if not model_class:
                self.logger.error(f"不支持的操作类型: {action} / Unsupported action type: {action}")
                return None
            
            # 验证和转换数据 / Validate and convert data
            validated_data = model_class(**raw_data)
            self.logger.info(f"成功解析{action}数据 / Successfully parsed {action} data")
            
            return validated_data
            
        except ValidationError as e:
            self.logger.error(f"数据验证失败 / Data validation failed: {str(e)}")
            raise
        except Exception as e:
            self.logger.error(f"解析请求数据时发生错误 / Error occurred while parsing request data: {str(e)}")
            return None
    
    async def format_response(self, data: Any) -> Dict[str, Any]:
        """
        格式化L16设备响应数据
        Format L16 device response data
        
        Args:
            data (Any): 响应数据 / Response data
            
        Returns:
            Dict[str, Any]: 格式化后的响应 / Formatted response
        """
        try:
            if isinstance(data, dict):
                # 如果是字典，直接返回标准格式 / If dict, return standard format directly
                return {
                    "status": data.get("status", 1),
                    "message": data.get("message", "处理成功 / Processing successful"),
                    "data": data.get("data", {})
                }
            else:
                # 默认成功响应格式 / Default success response format
                return {
                    "status": 1,
                    "message": "处理成功 / Processing successful",
                    "data": data if data else {}
                }
                
        except Exception as e:
            self.logger.error(f"格式化响应数据时发生错误 / Error occurred while formatting response data: {str(e)}")
            return {
                "status": 0,
                "message": f"响应格式化失败 / Response formatting failed: {str(e)}",
                "data": {}
            }
    
    async def validate_request(self, data: Dict[str, Any]) -> bool:
        """
        验证L16设备请求数据
        Validate L16 device request data
        
        Args:
            data (Dict[str, Any]): 请求数据 / Request data
            
        Returns:
            bool: 验证结果 / Validation result
        """
        try:
            # 检查必要字段 / Check required fields
            required_fields = ["device_id", "action", "timestamp"]
            for field in required_fields:
                if field not in data:
                    self.logger.error(f"缺少必要字段: {field} / Missing required field: {field}")
                    return False
            
            # 检查设备ID格式 / Check device ID format
            device_id = data.get("device_id")
            if not isinstance(device_id, str) or len(device_id) != 15:
                self.logger.error("设备ID格式错误 / Invalid device ID format")
                return False
            
            # 检查操作类型 / Check action type
            action = data.get("action")
            if not L16DataModels.validate_action(action):
                self.logger.error(f"不支持的操作类型: {action} / Unsupported action type: {action}")
                return False
            
            # 检查时间戳 / Check timestamp
            timestamp = data.get("timestamp")
            if not isinstance(timestamp, int) or timestamp <= 0:
                self.logger.error("时间戳格式错误 / Invalid timestamp format")
                return False
            
            self.logger.debug("请求数据验证通过 / Request data validation passed")
            return True
            
        except Exception as e:
            self.logger.error(f"验证请求数据时发生错误 / Error occurred while validating request data: {str(e)}")
            return False
    
    def get_protocol_version(self) -> str:
        """
        获取协议版本
        Get protocol version
        
        Returns:
            str: 协议版本 / Protocol version
        """
        return self.protocol_version
    
    def get_supported_actions(self) -> list:
        """
        获取支持的操作类型
        Get supported action types
        
        Returns:
            list: 支持的操作列表 / List of supported actions
        """
        return self.supported_actions.copy()
    
    async def format_error_response(self, error_code: int, error_message: str) -> Dict[str, Any]:
        """
        格式化错误响应
        Format error response
        
        Args:
            error_code (int): 错误代码 / Error code
            error_message (str): 错误消息 / Error message
            
        Returns:
            Dict[str, Any]: 错误响应 / Error response
        """
        return {
            "status": 0,
            "error_code": error_code,
            "message": error_message,
            "data": {}
        }
    
    async def format_command_request(self, device_id: str, command: Dict[str, Any]) -> Dict[str, Any]:
        """
        格式化命令请求数据
        Format command request data
        
        Args:
            device_id (str): 设备ID / Device ID
            command (Dict[str, Any]): 命令数据 / Command data
            
        Returns:
            Dict[str, Any]: 格式化的命令请求 / Formatted command request
        """
        try:
            formatted_command = {
                "url": command.get("url", "/sendDeviceInstructions"),
                "body": {
                    "imei": device_id,
                    **command.get("body", {})
                }
            }
            
            self.logger.info(f"格式化命令请求: {device_id} / Formatted command request: {device_id}")
            return formatted_command
            
        except Exception as e:
            self.logger.error(f"格式化命令请求时发生错误 / Error occurred while formatting command request: {str(e)}")
            raise